﻿using xjjxmm.auth.api.domain.ApiPermission.Repository;
using XjjXmm.Infrastructure.Exceptions;
using XjjXmm.Infrastructure.Mapper;
using XjjXmm.Message.Service.Model;
using XjjXmm.Message.Service.Publisher.Repository;

namespace XjjXmm.Message.Service.Publisher;

public class SqlPublisherService : IPublisher
{
    private readonly ITopicRepository topicRepository;
    private readonly IMessageRepository messageRepository;

    public SqlPublisherService(ITopicRepository topicRepository, IMessageRepository messageRepository)
    {
        this.topicRepository = topicRepository;
        this.messageRepository = messageRepository;
    }

    public async Task<bool> CreateTopic(TopicModel input)
    {
        var topic = await topicRepository.Find(input.Code);
        if(topic == null)
        {
            var entity = input.MapTo<TopicModel, TopicEntity>()!;
            entity.CreateTime = DateTime.Now;

            return await topicRepository.Add(entity);
        }

        throw new BussinessException("该主题已经存在");
    }

    public Task<bool> Publish(MessageModel input)
    {
        var entity = input.MapTo<MessageModel, MessageEntity>();

        return messageRepository.Add(entity);
    }
}
